/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.apps.realtyportal;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import mapviewballoons.example.custom.CustomItemizedOverlay;
import mapviewballoons.example.custom.CustomOverlayItem;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockListFragment;
import com.apps.essentials.ConsumeWebService;
import com.apps.realtyportal.HomeActivity.Exchanger;
import com.apps.realtyportal.LocationFragment.MapFragment;
import com.apps.realtyportal.LocationFragment.MyListFragment;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class PriceFragment extends SherlockListFragment {

	private MapFragment mMapFragment;
	private MyListFragment mMyListFragment;
	private Fragment mVisible = null;
	/** An array of items to display in ArrayList */
	String lists_of_prices[] = new String[] { 
			"200000.00",
			"300000.00",
			"400000.00",
			"500000.00",
			"600000.00",
			"700000.00",
			"800000.00",
			"900000.00",
			"1000000.00",
			"2000000.00",
			"3000000.00",
			"4000000.00",
			"5000000.00",
			"6000000.00",
			"7000000.00",
			"8000000.00",
			"9000000.00",
			"10000000.00"};
	//start here
	List<Overlay> newmapOverlays;
	ConsumeWebService cws;
	String centerAddress = "Cebu City";
	final String KEY_ADDRESS = "address";
	final String KEY_LAT = "latitude";
	final String KEY_LON = "longitude";
	final String KEY_NAME = "property_name";
	final String KEY_DESCRIPTION = "property_description";
	final String KEY_PRICE = "price";
	final String KEY_TYPE = "propertyType";
	double priceselected;
	private ActionBar actionbar;
	ArrayList pname = new ArrayList();	  
	ArrayList pdescription = new ArrayList();	  
	ArrayList pprice = new ArrayList();	  
	ArrayList wsData = new ArrayList();
	ArrayList listAdd = new ArrayList();
	ArrayList listoflat = new ArrayList();	  
	ArrayList listoflon = new ArrayList();
	ArrayList arptype = new ArrayList();
	ArrayList nearpricelat = new ArrayList();
	ArrayList nearpricelon = new ArrayList();
	
	MapController controlmap;
	CustomItemizedOverlay<CustomOverlayItem> newitemizedOverlay2;
	String selectedType;
	GeoPoint gp;
	Drawable drawable;
	int minLat = Integer.MAX_VALUE;
	int minLong = Integer.MAX_VALUE;
	int maxLat = Integer.MIN_VALUE;
	int maxLong = Integer.MIN_VALUE;
	double convertprice;
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {

	}

	public void onRestoreInstanceState(Bundle savedInstanceState) {

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		// super.onListItemClick(l, v, position, id);
		Toast.makeText(getSherlockActivity(), "position" + position,
				Toast.LENGTH_SHORT).show();

		Activity activity = getActivity();
		
		
		//String priceselected = (String)lists_of_prices[position];

//		cws = new ConsumeWebService();
//		String dataws = cws.getAllProperty();
		final String jsonData = 
	    		"[{\"property_id\":7,\"property_name\":\"Avialon\",\"property_description\":\"two stories, three stories\",\"price\":\"210000.00\",\"latitude\":\"10.312839\",\"longitude\":\"123.894389\",\"address\":\"Ibabao, Basak Pardo, Cebu City\",\"propertyType\":\"house\"}," +
	    		"{\"property_id\":8,\"property_name\":\"Spolarium\",\"property_description\":\"nice description, sample lang\",\"price\":\"310000.00\",\"latitude\":\"10.314528\",\"longitude\":\"123.896449\",\"address\":\"basak, pardo, cebu city\",\"propertyType\":\"building\"}," +
	    		"{\"property_id\":9,\"property_name\":\"NorthWest\",\"property_description\":\"sample lang gain, nice description\",\"price\":\"423456.00\",\"latitude\":\"10.313599\",\"longitude\":\"123.898208\",\"address\":\"Ibabao, Basak Pardo, Cebu City\",\"propertyType\":\"subdivision\"}," +
	    		"{\"property_id\":10,\"property_name\":\"Facific\",\"property_description\":\"hundred fold stories\",\"price\":\"3000000.00\",\"latitude\":\"10.312617\",\"longitude\":\"123.886428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"building\"},"+
	    		"{\"property_id\":11,\"property_name\":\"NorWay\",\"property_description\":\"hundred fold stories\",\"price\":\"400000.00\",\"latitude\":\"10.314617\",\"longitude\":\"123.896428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"house\"},"+
	    		"{\"property_id\":12,\"property_name\":\"EastWing\",\"property_description\":\"hundred stories\",\"price\":\"500000.00\",\"latitude\":\"10.316617\",\"longitude\":\"123.856428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"Condominium\"},"+
	    		"{\"property_id\":13,\"property_name\":\"WestWing\",\"property_description\":\"hundred stories\",\"price\":\"600000.00\",\"latitude\":\"10.315617\",\"longitude\":\"123.866428\",\"address\":\"Tass, Basak Pardo, Cebu City\",\"propertyType\":\"subdivision\"},"+
	    		"{\"property_id\":14,\"property_name\":\"NorthWing\",\"property_description\":\"hundred stories\",\"price\":\"601000.00\",\"latitude\":\"10.313617\",\"longitude\":\"123.876428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"house\"},"+
	    		"{\"property_id\":15,\"property_name\":\"SouthWing\",\"property_description\":\"hundred stories\",\"price\":\"700000.00\",\"latitude\":\"10.315617\",\"longitude\":\"123.896428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"building\"},"+
	    		"{\"property_id\":16,\"property_name\":\"Antartic\",\"property_description\":\"hundred stories\",\"price\":\"800000.00\",\"latitude\":\"10.316617\",\"longitude\":\"123.836428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"subdivision\"},"+
	    		"{\"property_id\":17,\"property_name\":\"Atlantic\",\"property_description\":\"hundred stories\",\"price\":\"900000.00\",\"latitude\":\"10.317617\",\"longitude\":\"123.856428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"house\"},"+
	    		"{\"property_id\":18,\"property_name\":\"Titanium\",\"property_description\":\"hundred stories\",\"price\":\"1000000.00\",\"latitude\":\"10.318617\",\"longitude\":\"123.866428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"building\"},"+
	    		"{\"property_id\":19,\"property_name\":\"Colurom\",\"property_description\":\"inspired by byby\",\"price\":\"200000.00\",\"latitude\":\"10.313617\",\"longitude\":\"123.836428\",\"address\":\"Ubos, Basak Pardo, Cebu City\",\"propertyType\":\"condomenium\"},"+
	    		"{\"property_id\":20,\"property_name\":\"ulayan\",\"property_description\":\"cool\",\"price\":\"3000000.00\",\"latitude\":\"10.317768\",\"longitude\":\"123.885655\",\"address\":\"Tunga, Basak Pardo, Cebu City\",\"propertyType\":\"condomenium\"}]";   		
	    		
		newmapOverlays = HomeActivity.Exchanger.mMapView.getOverlays();
		newmapOverlays.clear();
		HomeActivity.Exchanger.mMapView.setBuiltInZoomControls(true);
		controlmap = HomeActivity.Exchanger.mMapView.getController();
		
		if (activity != null) {
			
			DecimalFormat df = new DecimalFormat("#,###.##");
			priceselected = Double.valueOf(lists_of_prices[position].toString()).doubleValue();
			
			Toast.makeText(getSherlockActivity(), "Price selected "+priceselected, Toast.LENGTH_LONG).show();
			try {
				JSONArray array = new JSONArray(jsonData);
				
				for (int i = 0; i < array.length(); i++) {
					
					JSONObject e = array.getJSONObject(i);
					String coListLat = e.getString(KEY_LAT);
					String coListLon = e.getString(KEY_LON);
					  
					String copname = e.getString(KEY_NAME);
					String copdescription = e.getString(KEY_DESCRIPTION);
					String copprice = e.getString(KEY_PRICE);
					String coptype = e.getString(KEY_TYPE);
					listoflat.add(coListLat);
					listoflon.add(coListLon);
					pname.add(copname);
					pdescription.add(copdescription);
					pprice.add(copprice);
					arptype.add(coptype);
				}
				
				
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString());
			}
			
			for(int i = 0; i<pprice.size(); i++){
			//double nearestprice = Double.valueOf(pprice.get(i).toString()).doubleValue();;
//			  double nearestprice = Double.parseDouble(pprice.get(i).toString());
			  String nearestprice = pprice.get(i).toString().replace(",", "");
			  		convertprice = Double.valueOf(nearestprice).doubleValue();
			  		//double result = Double.valueOf(convertprice * priceselected).doubleValue();
			//Toast.makeText(getSherlockActivity(), "priceselected: "+priceselected+" converted price: "+convertprice +" result "+result, Toast.LENGTH_LONG).show();
			double priceinterval = Double.valueOf(100000.00).doubleValue();
			double addedprice = priceselected+priceinterval;
			
			String spname = pname.get(i).toString();
			String spdesc = pdescription.get(i).toString();
			
			String sptype = arptype.get(i).toString();
			if(convertprice>=priceselected){
				if(convertprice<addedprice){
				if(priceselected<addedprice){					
					Toast.makeText(getSherlockActivity(), "priceselected: "+priceselected +" converted price "+convertprice +" added price "+addedprice, Toast.LENGTH_LONG).show();
					String spprice = pprice.get(i).toString();
					double dlistwlat = Double.parseDouble((String) listoflat.get(i));
					double dlistwlon = Double.parseDouble((String) listoflon.get(i));
					int listwlat = (int) (dlistwlat * 1E6);
					int listwlon = (int) (dlistwlon * 1E6);
					//Toast.makeText(getSherlockActivity(), "Price "+p///, Toast.LENGTH_LONG).show();
					
					gp = new GeoPoint(listwlat, listwlon);
					minLat  = (int) Math.min( gp.getLatitudeE6(), minLat );
				    minLong = (int) Math.min( gp.getLongitudeE6(), minLong);
				    maxLat  = (int) Math.max( gp.getLatitudeE6(), maxLat );
				    maxLong = (int) Math.max( gp.getLongitudeE6(), maxLong );	
					if(sptype.equals("building")){
						drawable = getResources().getDrawable(R.drawable.building2);
					}else if(sptype.equals("house")){
						drawable = getResources().getDrawable(R.drawable.house2);
					}else if(sptype.equals("subdivision")){
						drawable = getResources().getDrawable(R.drawable.subdivision2);
					}
										
					//drawable = getResources().getDrawable(R.drawable.mark_blue);
					
			
					  newitemizedOverlay2 = new CustomItemizedOverlay<CustomOverlayItem>(drawable, HomeActivity.Exchanger.mMapView);
					  CustomOverlayItem overlayItem3 = new CustomOverlayItem(gp, ""+spname, 
								""+spdesc,"","","","","","",
								"http://ia.media-imdb.com/images/M/MV5BMjAyNjk5Njk0MV5BMl5BanBnXkFtZTcwOTA4MjIyMQ@@._V1._SX40_CR0,0,40,54_.jpg");
						newitemizedOverlay2.addOverlay(overlayItem3);
						newmapOverlays.add(newitemizedOverlay2);
						newitemizedOverlay2.populateNow();
					}
				}
			}			
		}
			// Fragments have access to their parent Activity's FragmentManager.
			// You can.
			// obtain the FragmentManager like this.
			FragmentManager fm = getFragmentManager();

			if (fm != null) {

				// Perform the FragmentTransaction to load in the list tab
				// content.
				// Using FragmentTransaction#replace will destroy any Fragments
				// currently inside R.id.fragment_content and add the new
				// Fragment
				// in its place.
				// FragmentTransaction ft = fm.beginTransaction();
				// ft.replace(android.R.id.content, new MapFragment());
				// ft.commit();

				Fragment productDetailFragment = new MapFragment();
				FragmentTransaction transaction = getFragmentManager().beginTransaction();
				transaction.addToBackStack(null);
				transaction.replace(android.R.id.content, productDetailFragment).commit();
			}

			// Display a simple Toast to demonstrate that the click event is
			// working. Notice that Fragments have a
			// getString() method just like an Activity, so that you can quickly
			// access your localized Strings.
			controlmap.zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
			controlmap.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
			HomeActivity.Exchanger.mMapView.invalidate();
			listoflat.clear();
			listoflon.clear();
			pname.clear();
			pdescription.clear();
			pprice.clear();
			arptype.clear();
		//	Toast.makeText(activity, "Pooop" + "  " + "tae", Toast.LENGTH_SHORT)
			//		.show();
			
		}

	}
	


	// @Override
	// public void onCreate(Bundle savedInstanceState) {
	// requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
	// // This has to be called before setContentView and you must use the
	// // class in com.actionbarsherlock.view and NOT android.view
	// requestWindowFeature(Window.FEATURE_PROGRESS);
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.main);
	//
	// // We instantiate the MapView here, it's really important!
	// Exchanger.mMapView = new MapView(this,
	// "0P9evGBeKSCPTOeo6QNz-E9sdRKSgNFXBW0kv1Q"); // TODO: Replace for
	// // API Key!
	//
	// setupFragments();
	// // We manually show the list Fragment.
	// showFragment(mMyListFragment);
	//
	// }

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// View view = inflater.inflate(R.layout.try_main, container, false);
		// ** Creating array adapter to set data in listview */
		// requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);

		/** Creating array adapter to set data in listview */
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
				.getBaseContext(), android.R.layout.simple_list_item_1,
				lists_of_prices);

		/** Setting the array adapter to the listview */
		setListAdapter(adapter);

		return super.onCreateView(inflater, container, savedInstanceState);

		/**
		 * This has to be called before setContentView and you must use the
		 * //class in com.actionbarsherlock.view and NOT android.view
		 * //requestWindowFeature(Window.FEATURE_PROGRESS);
		 * super.onCreate(savedInstanceState); View view =
		 * inflater.inflate(R.layout.main, container);
		 */
		/** Setting the array adapter to the listview */

	}

	@Override
	public void onStart() {
		super.onStart();
		// HomeActivity h = new HomeActivity();
		// actionbar = h.getSupportActionBar();
		// actionbar.setDisplayHomeAsUpEnabled(true);
		/** Setting the multiselect choice mode for the listview */
		getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);

	}

	/**
	 * This method does the setting up of the Fragments. It basically checks if
	 * the fragments exist and if they do, we'll hide them. If the fragments
	 * don't exist, we create them, add them to the FragmentManager and hide
	 * them.
	 */
	// private void setupFragments() {
	// final FragmentTransaction ft = getSupportFragmentManager()
	// .beginTransaction();
	//
	// /*
	// * If the activity is killed while in BG, it's possible that the
	// * fragment still remains in the FragmentManager, so, we don't need to
	// * add it again.
	// */
	// mMapFragment = (MapFragment) getSupportFragmentManager()
	// .findFragmentByTag(MapFragment.TAG);
	// if (mMapFragment == null) {
	// mMapFragment = new MapFragment();
	// ft.add(R.id.fragment_container, mMapFragment, MapFragment.TAG);
	// }
	// ft.hide(mMapFragment);
	//
	// mMyListFragment = (MyListFragment) getSupportFragmentManager()
	// .findFragmentByTag(MyListFragment.TAG);
	// if (mMyListFragment == null) {
	// mMyListFragment = new MyListFragment();
	// ft.add(R.id.fragment_container, mMyListFragment, MyListFragment.TAG);
	// }
	// ft.hide(mMyListFragment);
	//
	// ft.commit();
	// }

	/**
	 * This method shows the given Fragment and if there was another visible
	 * fragment, it gets hidden. We can just do this because we know that both
	 * the mMyListFragment and the mMapFragment were added in the Activity's
	 * onCreate, so we just create the fragments once at first and not every
	 * time. This will avoid facing some problems with the MapView.
	 * 
	 * @param fragmentIn
	 *            The fragment to show.
	 */
	// private void showFragment(Fragment fragmentIn) {
	// if (fragmentIn == null)
	// return;
	//
	// final FragmentTransaction ft = getSupportFragmentManager()
	// .beginTransaction();
	// ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
	//
	// if (mVisible != null)
	// ft.hide(mVisible);
	//
	// ft.show(fragmentIn).commit();
	// mVisible = fragmentIn;
	// }

	/**
	 * This class acts as an exchanger between the Activity and the MapFragment,
	 * so if you want, you can put the MapFragment class in a separate java
	 * file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class Exchanger {
		// We will use this MapView always.
		public static MapView mMapView;
	}

	/**
	 * This is our ListFragment class. You can put it in a separate java file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class MyListFragment extends SherlockListFragment {

		public static final String TAG = "listFragment";

		private final String[] mItems = { "List Item 1", "List Item 2",
				"List Item 3", "List Item 4", "List Item 5", "List Item 6",
				"List Item 7", "List Item 8", "List Item 9", "List Item 10" };

		public MyListFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// Inflate the ListView layout file.
			return inflater.inflate(R.layout.list_fragment, null);
		}

		@Override
		public void onViewCreated(View arg0, Bundle arg1) {
			super.onViewCreated(arg0, arg1);
			setListAdapter(new ArrayAdapter<String>(getSherlockActivity(),
					android.R.layout.simple_list_item_1, android.R.id.text1,
					mItems));
		}
	}

	/**
	 * This is the Fragment class that will hold the MapView as its content
	 * view. You can put it in a separate java file.
	 * 
	 * @author Xavi
	 * 
	 */
	public static class MapFragment extends SherlockFragment {

		public static final String TAG = "mapFragment";

		public MapFragment() {
		}

		@Override
		public void onCreate(Bundle arg0) {
			super.onCreate(arg0);
			setRetainInstance(true);
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup vg,
				Bundle data) {
			// The Activity created the MapView for us, so we can do some init
			// stuff.
			// View v = inflater.inflate(R.layout.main, vg, false);

			final ViewGroup parent = (ViewGroup) HomeActivity.Exchanger.mMapView
					.getParent(); 

			if (parent != null)
				parent.removeView(HomeActivity.Exchanger.mMapView);

			HomeActivity.Exchanger.mMapView.setClickable(true);


			/*
			 * If you're getting Exceptions saying that the MapView already has
			 * a parent, uncomment the next lines of code, but I think that it
			 * won't be necessary. In other cases it was, but in this case I
			 * don't this should happen.
			 */
			/*
			 * final ViewGroup parent = (ViewGroup)
			 * Exchanger.mMapView.getParent(); if (parent != null)
			 * parent.removeView(Exchanger.mMapView);
			 */

			return HomeActivity.Exchanger.mMapView;
		}
	}

}